<?php

namespace backend\modules\Sys\modules\Rbac\modules\Admin\controllers;

use backend\models\c2\entity\rest\BeUser;
use backend\models\c2\entity\rest\BeUserProfile;
use common\models\c2\statics\EntityModelStatus;
use common\rest\controllers\AuthController;
use common\rest\models\c2\statics\ResponseDatum;
use Yii;
use yii\web\NotFoundHttpException;

/**
 * Default controller for the `admin` module
 */
class ProfileController extends AuthController
{

    public $modelClass = 'backend\models\c2\entity\rest\BeUserProfile';

    /**
     * @param null $id
     * @return array
     * @throws NotFoundHttpException
     */
    public function actionEdit($id = null)
    {
        /** @var BeUserProfile $model */
        $model = $this->retrieveModel($id);
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return ResponseDatum::getSuccessDatum(['isNewRecord' => $model->isNewRecord, 'primaryKeys' => ['id' => $model->id]]);
            } else {
                return ResponseDatum::getErrorDatum($model->errors);
            }
        }
        return ResponseDatum::getSuccessDatum([
            'inputItems' => $model->buildInputItems(),
            'modelForm' => $model->formName(),
            'isNewRecord' => $model->isNewRecord,
        ]);
    }

    public function retrieveModel($id = null, $allowReturnNew = true)
    {
        $model = BeUserProfile::find()->where(['user_id' => $id])->one();
        if ($model == null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Finds the BeUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return array|BeUserProfile
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = BeUserProfile::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
